package com.bestvike.stone.core.threading.holder;

import com.bestvike.stone.core.threading.ThreadUtils;
import org.springframework.util.Assert;

/**
 * 任务或子线程开始执行时调用,将父线程数据复制到任务或子线程
 * Created by 许崇雷 on 2018/8/14.
 */
public final class RawThreadLocalsHolder implements AutoCloseable {
    private final Thread thread;
    private final Object threadLocals;
    private final Object inheritableThreadLocals;

    public RawThreadLocalsHolder(CopyThreadLocalsHolder copyThreadLocalsHolder) {
        Assert.notNull(copyThreadLocalsHolder, "copyThreadLocalsHolder can not be null");
        //备份数据
        this.thread = Thread.currentThread();
        this.threadLocals = ThreadUtils.getThreadLocals(this.thread);
        this.inheritableThreadLocals = ThreadUtils.getInheritableThreadLocals(this.thread);
        //开始继承
        ThreadUtils.setThreadLocals(this.thread, null);
        ThreadUtils.setInheritableThreadLocals(this.thread, copyThreadLocalsHolder.getInheritableThreadLocals());
    }

    public Thread getThread() {
        return this.thread;
    }

    public Object getThreadLocals() {
        return this.threadLocals;
    }

    public Object getInheritableThreadLocals() {
        return this.inheritableThreadLocals;
    }

    @Override
    public void close() {
        //还原数据
        ThreadUtils.setThreadLocals(this.thread, this.threadLocals);
        ThreadUtils.setInheritableThreadLocals(this.thread, this.inheritableThreadLocals);
    }
}
